/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.client.network;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author czarek
 */
public class NetworkStats implements INetworkStats {

    private final Collection<Reference<TrafficEntry>> entries 
            = new java.util.concurrent.ConcurrentLinkedQueue<Reference<TrafficEntry>>();

    @Override
    public void read(int bytes) {
        if (bytes > 0) {
            Reference<TrafficEntry> ref= new SoftReference<TrafficEntry>(new TrafficEntry(bytes));
            entries.add(ref);
        }
    }

    @Override
    public long countStatsFor(final int lastMilis) {
        final long minTime = System.currentTimeMillis() - lastMilis;
        //final int maxNullHits = 300;
        //int nullHits = 0;
        final Iterator<Reference<TrafficEntry>> iter = entries.iterator();

        long bytes = 0;
        while (iter.hasNext()) {
            TrafficEntry ref = iter.next().get();
            if (ref == null) {
                //assert (++nullHits < maxNullHits);
                iter.remove();
            } else if (ref.getTime() < minTime) {
                iter.remove();
            } else {
                bytes += ref.getSize();
                break;
            }
        }
        while (iter.hasNext()) {
            TrafficEntry ref = iter.next().get();
            if (ref != null) {
                bytes += ref.getSize();
            }
        }


        return bytes;
    }
}
